package salutem.Telas;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import salutem.Beans.ModuloBean;
import salutem.Beans.UsuarioBean;
import salutem.DAO.PermissaoDAO;
import salutem.DAO.UsuarioDAO;
import salutem.Utils.MenuDinamico;
import salutem.Utils.Msg;

/**
 *
 * @author Renato Doretto
 */
public class TelaLogin extends javax.swing.JDialog {

    private UsuarioDAO daoUsuario;
    private PermissaoDAO daoPerm;
    private TelaPrincipal principal;

    public TelaLogin(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        //this.setIconImage(new ImageIcon(getClass().getResource("/salutem/imagens/icone-sistema.png")).getImage());
        this.setSize(350, 290);
        this.setLocationRelativeTo(null);

        this.daoUsuario = new UsuarioDAO();
        this.daoPerm = new PermissaoDAO();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * alwa%ys regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btLogar = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txUsuario = new javax.swing.JTextField();
        txSenha = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("LOGIN DE ACESSO");
        setResizable(false);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btLogar.setText("Logar");
        btLogar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLogarActionPerformed(evt);
            }
        });
        getContentPane().add(btLogar, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 190, 110, 27));

        btCancelar.setText("Cancelar");
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 190, 104, 27));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel1.setText("Usuário:");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 100, -1, -1));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Senha:");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 140, -1, -1));
        getContentPane().add(txUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 100, 148, -1));

        txSenha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txSenhaFocusGained(evt);
            }
        });
        txSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txSenhaKeyTyped(evt);
            }
        });
        getContentPane().add(txSenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 140, 148, -1));

        jLabel3.setFont(new java.awt.Font("Verdana", 1, 18));
        jLabel3.setForeground(new java.awt.Color(0, 51, 153));
        jLabel3.setText("SALUTEM");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 30, -1, -1));

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 90, 270, 80));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        this.setVisible(false);
        System.exit(0);
    }//GEN-LAST:event_btCancelarActionPerformed

    private void btLogarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLogarActionPerformed
        this.logar();
    }//GEN-LAST:event_btLogarActionPerformed

    private void txSenhaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txSenhaFocusGained
        this.txSenha.selectAll();
    }//GEN-LAST:event_txSenhaFocusGained

    private void txSenhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txSenhaKeyTyped
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            this.logar();
        }
    }//GEN-LAST:event_txSenhaKeyTyped

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        this.repaint();
    }//GEN-LAST:event_formWindowGainedFocus

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        this.txUsuario.requestFocus();
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TelaLogin dialog = new TelaLogin(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btLogar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPasswordField txSenha;
    private javax.swing.JTextField txUsuario;
    // End of variables declaration//GEN-END:variables

    private void criarMenu(Component componentePai, int idFuncionario, Integer idModuloPai) throws SQLException {
        this.daoPerm.consultarMenu(idFuncionario, idModuloPai);

        ResultSet RS = this.daoPerm.getRS();

        while (RS.next()) {

            ModuloBean modulo = new ModuloBean();
            modulo.setIdModulo(RS.getInt("idModulo"));
            modulo.setDescricao(RS.getString("descricao"));
            modulo.setNomeTela(RS.getString("nomeTela"));

            if (RS.getInt("Itens") > 0) { // Tem Itens Filhos

                JMenu menu = new JMenu(RS.getString("descricao").trim());

                if (RS.getString("nomeTela") != null) {
                    menu.addMouseListener(new MenuDinamico(this.principal, RS.getString("nomeTela"), modulo));
                }

                if (idModuloPai == null) { // Menu Raiz
                    ((JMenuBar) componentePai).add(menu);
                } else {
                    ((JMenu) componentePai).add(menu);
                }

                this.criarMenu(menu, idFuncionario, RS.getInt("idModulo"));

            } else {

                if (idModuloPai == null) { // É menu raiz, mas sem itens

                    JMenu menu = new JMenu(RS.getString("descricao").trim());

                    if (RS.getString("nomeTela") != null) {
                        menu.addMouseListener(new MenuDinamico(this.principal, RS.getString("nomeTela"), modulo));
                    }

                    ((JMenuBar) componentePai).add(menu);

                } else { // É item

                    JMenuItem menuItem = new JMenuItem(RS.getString("descricao").trim());

                    if (RS.getString("nomeTela") != null) {
                        menuItem.addActionListener(new MenuDinamico(this.principal, RS.getString("nomeTela"), modulo));
                    }

                    ((JMenu) componentePai).add(menuItem);

                }

            }
        }
    }

    private void logar() {
        try {
            this.daoUsuario.logar(this.txUsuario.getText(), this.txSenha.getText());
            UsuarioBean usuario = daoUsuario.getUsuario(this.txUsuario.getText(), this.txSenha.getText());

            this.setVisible(false);

            this.principal = new TelaPrincipal();
            this.principal.setUsuario(usuario);

            this.principal.lbIdentificacao.setText(usuario.getFuncionario().getNome().trim().toUpperCase());

            if (usuario.getFuncionario().getSexo().equalsIgnoreCase("F")) {
                this.principal.lbIdentificacao.setIcon(new ImageIcon(getClass().getResource("/salutem/imagens/woman.png")));
            } else {
                this.principal.lbIdentificacao.setIcon(new ImageIcon(getClass().getResource("/salutem/imagens/man.png")));
            }

            // Menu Recursivo >>>
            this.daoPerm.setConnection("sal");
            this.daoPerm.open();

            this.criarMenu(this.principal.barraMenu, usuario.getIdUsuario(), null);

            this.daoPerm.close();
            // Menu Recursivo >>>

            JMenuItem altSenha = new JMenuItem("Alterar Senha");
            altSenha.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    TelaConfigSenha t = new TelaConfigSenha(principal, true);
                    t.setLocationRelativeTo(null);
                    t.setVisible(true);
                }
            });

            JMenu menuConfig = new JMenu("Configurações");
            menuConfig.add(altSenha);

            JMenuItem logoff = new JMenuItem("Logoff");
            logoff.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    logoff();
                }
            });

            JMenuItem sair = new JMenuItem("Sair do Sistema");
            sair.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    sair();
                }
            });

            JMenu menuSair = new JMenu("Sair");
            menuSair.add(logoff);
            menuSair.add(sair);

            this.principal.barraMenu.add(menuConfig);
            this.principal.barraMenu.add(menuSair);
            this.principal.setLocationRelativeTo(null);
            this.principal.setExtendedState(TelaPrincipal.MAXIMIZED_BOTH);

            this.principal.setVisible(true);

            this.dispose();
        } catch (SQLException ex) {
            if (ex.getMessage().equals("USUARIO-INVALIDO")) {
                Msg.erro(this, "Usuário e/ou senha inválidos!");
                this.txSenha.requestFocus();
                this.txSenha.selectAll();
            } else {
                Msg.erro(this, "Erro: " + ex.getMessage());
            }
        }
    }

    private void logoff() {
        if (Msg.confirmar(this, "Deseja realmente fazer logoff ?")) {
            try {
                Runtime.getRuntime().exec("cmd /c salutem.jar 1");
                System.exit(0);
            } catch (IOException ex) {
                Msg.erro(null, "Erro ao fazer logoff!\n\n" + ex.getMessage());
            }
        }
    }

    private void sair() {
        if (Msg.confirmar(this, "Deseja realmente sair do sistema ?")) {
            this.setVisible(false);
            System.exit(0);
        }
    }
}
